package 反射6;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
 * @Auther:lele
 * @Date:2025/3/18
 */
public class JdbcTemplateDemo2 {
    //1. 获取JDBCTemplate对象
    private static JdbcTemplate template = new JdbcTemplate(JDBCUtils1.getDataSource());

    /**
     * 1. 添加一条记录
     */
    @Test
    public void test2() {
        String sql = "insert into user(admin,password,money,id) values(?,?,?,null)";
        int count = template.update(sql,  "wang","12333",49999);
        System.out.println(count);

    }

    @Test
    public void test3() {
        String sql = "delete from user where id = ?";
        int count = template.update(sql, 12);
        System.out.println(count);
    }


    /**
     * 4.查询id为1001的记录，将其封装为Map集合
     * 注意：这个方法查询的结果集长度只能是1
     */
    @Test
    public  void test4() {
        String sql = "select * from user where id = ?";
        Map<String, Object> map = template.queryForMap(sql, 13);
        System.out.println(map);
        System.out.println("User ID: " + map.get("id"));
        System.out.println("Name: " + map.get("admin"));
        System.out.println("Email: " + map.get("password"));
        //{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}

    }


    /**
     * 5. 查询所有记录，将其封装为List
     */
    @Test
    public void test5() {
        String sql = "select * from user";
        List<Map<String, Object>> list = template.queryForList(sql);

        for (Map<String, Object> stringObjectMap : list) {
            System.out.println(stringObjectMap);
        }
    }

    /**
     * 6. 查询所有记录，将其封装为Emp对象的List集合
     */
    @Test
    public void test6() {
        String sql = "select * from user";
        List<user> list = template.query(sql, new RowMapper<user>() {

            @Override
            public user mapRow(ResultSet rs, int i) throws SQLException {
                user emp = new user();
                int id = rs.getInt("id");
                String admin = rs.getString("admin");
                String password = rs.getString("password");
                int money = rs.getInt("money");

                emp.setId(id);
                emp.setAdmin(admin);
                emp.setPassword(password);
                emp.setMoney(String.valueOf(money));

                return emp;
            }
        });


        for (user emp : list) {
            System.out.println(emp.getAdmin());
        }
    }

    //    一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
    @Test
    public void test6_2() {

        String sql = "select * from user";
        List<user> list = template.query(sql, new BeanPropertyRowMapper<user>(user.class));
        for (user emp : list) {
            System.out.println(emp);
        }
    }
}
